//
//  SQNewDetailsViewController.m
//  energy
//
//  Created by 苏青 on 2021/10/11.
//

#import "SQNewDetailsViewController.h"

#import "SQNewDetailsModel.h"

#import "WorkDetailViewController.h"
#import "SVProgressHUD.h"
#import <WebKit/WebKit.h>

@interface SQNewDetailsViewController ()<BaseTableVCInterface,WKUIDelegate,WKNavigationDelegate>
@property (weak, nonatomic) IBOutlet WKWebView *webView;

@end

@implementation SQNewDetailsViewController

- (void)viewDidLoad {
    self.tableViewInterface = self;
    [super viewDidLoad];
    self.navigationItem.title = @"新闻公告";
    [self getNewDetailsData];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate =self;
    self.webView.opaque = NO;
    self.webView.scrollView.bounces = NO;//禁止滑动
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getReleaseData) name:@"addRelease" object:nil];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getNewDetailsData];
    }];
    
//    [self.webView addObserver:self forKeyPath:@"scrollView.contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
}

-(void)getNewDetailsData{
    [SQNewDetailsModel getDataWithParams:@{@"a_id":self.a_id,@"a_enterprise":MEnterpriseText} WithCallBack:^(SQNewDetailsModel * data) {
        [self detailModelwithArr:data.files withCallBack:nil];
      
        NSString * htmlStr = [data.data.a_content stringByReplacingOccurrencesOfString:@"img src=\""withString:@"img src=\"http://government.anjiesws.com"];
        
        
       
            [self.webView loadHTMLString:[self adaptWebViewForHtml:htmlStr] baseURL:nil];
        
//        [self reloadTableView];
    }];
}

-(BaseModel *)modelForCell:(NSIndexPath *)indexPath{
    return self.dataSouece[indexPath.row];
}



-(NSInteger)rowsCount:(NSInteger)section{
    return self.dataSouece.count;
}


- (NSArray<NSArray<NSString *> *> *)classArr{
    return @[@[@"SQNewDetailsTableViewCell"]];
}

- (void)tableViewSelectAtIndexPath:(NSIndexPath *)indexPath{
    SQNewDetailsModelFiles * dataModel = self.dataSouece[indexPath.row];
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 获取Caches目录
                    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

                    NSString * filePath = [cachesPath stringByAppendingFormat:@"/%@",dataModel.af_name];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    if ([fileManager fileExistsAtPath:filePath]) {

                    }else{
                    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://government.anjiesws.com%@",dataModel.af_enclosure]];
                    NSData *data = [NSData dataWithContentsOfURL:url];
                    NSString * filePath = filePath = [self addFile:dataModel.af_name contents:data];
                    }
        NSLog(@"%@",filePath);
        if (filePath.length != 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                WorkDetailViewController *vc = WorkDetailViewController.new;
                vc.filePath = filePath;
                vc.n_title = dataModel.af_name;
                [self pushVC:vc];
            });
        }
        
    });
}

- (NSString *)addFile:(NSString *)filePath contents:(NSData *)data{
    // 获取Caches目录
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    filePath = [cachesPath stringByAppendingFormat:@"/%@",filePath];
    
    if (filePath.length==0) {
        return @"";
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return filePath;
    }
    NSError *error;
    NSString *dirPath = [filePath stringByDeletingLastPathComponent];
    BOOL isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creat File Failed:%@",[error localizedDescription]);
    }
    if (!isSuccess) {
        return @"";
    }
    isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    
    [data writeToFile:filePath atomically:YES];
    return filePath;
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 页面加载完成之后调用 此方法会调用多次
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
//    CGFloat height = 0.0;
    [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
           CGRect frame =webView.frame;
           frame.size.height =[result floatValue];
           webView.frame = frame;
//           self.scrollview.contentSize = CGSizeMake(SCREEN_WIDTH, ScaleHeight(296)+frame.size.height);
        self.tableView.tableHeaderView.height = frame.size.height;
//        self.webView.frame = CGRectMake(0, 0, W(355),webView.frame.size.height);
        SQ_LOG(@"height  =  %f",frame.size.height);
        [self reloadTableView];
       }];
  
//    height = webView.scrollView.contentSize.height;
//    self.webView.frame = CGRectMake(0, 0, W(355),webView.scrollView.contentSize.height);
//    self.tableView.tableHeaderView.height = height;
//    SQ_LOG(@"height  =  %f",height);
    
   
    
}

//HTML适配图片文字
- (NSString *)adaptWebViewForHtml:(NSString *) htmlStr
{
    NSMutableString *headHtml = [[NSMutableString alloc] initWithCapacity:0];
    [headHtml appendString : @"<html>" ];
    
    [headHtml appendString : @"<head>" ];
    
    [headHtml appendString : @"<meta charset=\"utf-8\">" ];
    
    [headHtml appendString : @"<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />" ];
    
    [headHtml appendString : @"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />" ];
    
    [headHtml appendString : @"<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />" ];
    
    [headHtml appendString : @"<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />" ];

    //适配图片宽度，让图片宽度等于屏幕宽度
    //[headHtml appendString : @"<style>img{width:100%;}</style>" ];
    //[headHtml appendString : @"<style>img{height:auto;}</style>" ];
    
     //适配图片宽度，让图片宽度最大等于屏幕宽度
//    [headHtml appendString : @"<style>img{max-width:100%;width:auto;height:auto;}</style>"];

    
   //适配图片宽度，如果图片宽度超过手机屏幕宽度，就让图片宽度等于手机屏幕宽度，高度自适应，如果图片宽度小于屏幕宽度，就显示图片大小
    [headHtml appendString : @"<script type='text/javascript'>"
     "window.onload = function(){\n"
     "var maxwidth=document.body.clientWidth;\n" //屏幕宽度
     "for(i=0;i <document.images.length;i++){\n"
     "var myimg = document.images[i];\n"
     "if(myimg.width > maxwidth){\n"
     "myimg.style.width = '100%';\n"
     "myimg.style.height = 'auto'\n;"
     "}\n"
     "}\n"
     "}\n"
     "</script>\n"];
    
    [headHtml appendString : @"<style>table{width:100%;}</style>" ];
    [headHtml appendString : @"<title>webview</title>" ];
    NSString *bodyHtml;
    bodyHtml = [NSString stringWithString:headHtml];
    bodyHtml = [bodyHtml stringByAppendingString:htmlStr];
    return bodyHtml;
    
}

//// 使用kvo监听到的contensize变化，之所以在这里设置，因为webview加载的内容多的时候 是一段一段加载初开的，所以webview的contensize是实时变化的，所以在这里监听到可以以达到实时改变，不至于页面卡顿
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//    if (object == self.webView && [keyPath isEqual:@"scrollView.contentSize"]) {
//        UIScrollView *scrollView = self.webView.scrollView;
//        self.webView.frame = CGRectMake(0, 0, W(355),scrollView.contentSize.height);
//        self.tableView.tableHeaderView.height = scrollView.contentSize.height;
//        [self reloadTableView];
////        CGSize size = CGSizeMake(SCREEN_WIDTH, ;
////        self.webview.frame = CGRectMake(0, MaxY(self.midView)+7+40, SCREEN_WIDTH, size.height);
////        self.scrollview.contentSize = CGSizeMake(SCREEN_WIDTH, ScaleHeight(296)+size.height);
//    }
//}

@end
